package group.program.Service.impl;
import group.program.Service.PdfService;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.text.PDFTextStripperByArea;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.text.PDFTextStripper;

import java.awt.geom.Rectangle2D;
import java.io.InputStream;
import java.io.IOException;

@Service
public class PdfServiceImpl implements PdfService {
    @Override
    public String extractInformation(MultipartFile file) {
        StringBuilder textBuilder = new StringBuilder();

        try (InputStream inputStream = file.getInputStream(); PDDocument document = PDDocument.load(inputStream)) {
            // 提取文本内容
            PDFTextStripper textStripper = new PDFTextStripper();
            String text = textStripper.getText(document);
            textBuilder.append(text).append("\n");
            // 提取表格内容
//            extractTablesFromDocument(document, textBuilder);

        } catch (IOException e) {
            e.printStackTrace();
            return "处理文件时出错。";
        }

        return textBuilder.toString();
    }

    private void extractTablesFromDocument(PDDocument document, StringBuilder textBuilder) throws IOException {
        PDFTextStripperByArea stripper = new PDFTextStripperByArea();

        // 遍历每一页
        for (PDPage page : document.getPages()) {
            // 定义表格提取区域
            Rectangle2D region = new Rectangle2D.Double(
                    page.getMediaBox().getLowerLeftX(), // 区域左下角 x 坐标
                    page.getMediaBox().getLowerLeftY(), // 区域左下角 y 坐标
                    page.getMediaBox().getWidth(),       // 区域宽度
                    page.getMediaBox().getHeight()       // 区域高度
            );
            // 添加区域以供表格提取
            stripper.addRegion("tableRegion", region);
            stripper.extractRegions(page);

            // 获取该区域的文本
            String tableText = stripper.getTextForRegion("tableRegion");

            // 将提取的表格文本添加到 StringBuilder 中
            if (!tableText.trim().isEmpty()) {
                textBuilder.append(tableText).append("\n");
            }
        }
    }
}